package com.qwc.blog.security.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qwc.blog.entity.User;
import com.qwc.blog.mapper.UserMapper;
import com.qwc.blog.security.entity.LoginUser;
import com.qwc.blog.security.exception.UserDisabledException;
import com.qwc.blog.security.exception.UserNotExistException;
import com.qwc.blog.common.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.qwc.blog.common.constant.CommonConstant.NO_INT;

/**
 * @author qwc
 * @Date 2021/10/15 10:16
 * 账号用户认证
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if (Objects.isNull(user)) {
            throw new UserNotExistException(username);
        } else if (NO_INT.equals(Integer.parseInt(user.getStatus()))) {
            throw new UserDisabledException(username);
        }
        return new LoginUser(user);
    }
}
